function getLocalFilePath(path) {
	if (path.indexOf('_www') === 0 || path.indexOf('_doc') === 0 || path.indexOf('_documents') === 0 || path.indexOf(
			'_downloads') === 0) {
		return path
	}
	if (path.indexOf('file://') === 0) {
		return path
	}
	if (path.indexOf('/storage/emulated/0/') === 0) {
		return path
	}
	if (path.indexOf('/') === 0) {
		var localFilePath = plus.io.convertAbsoluteFileSystem(path)
		if (localFilePath !== path) {
			return localFilePath
		} else {
			path = path.substr(1)
		}
	}
	return '_www/' + path
}

export function pathToBase64(path) {
	return new Promise(function(resolve, reject) {
		if (typeof window === 'object' && 'document' in window) {
			if (typeof FileReader === 'function') {
				var xhr = new XMLHttpRequest()
				xhr.open('GET', path, true)
				xhr.responseType = 'blob'
				xhr.onload = function() {
					if (this.status === 200) {
						let fileReader = new FileReader()
						fileReader.onload = function(e) {
							resolve(e.target.result)
						}
						fileReader.onerror = reject
						fileReader.readAsDataURL(this.response)
					}
				}
				xhr.onerror = reject
				xhr.send()
				return
			}
			var canvas = document.createElement('canvas')
			var c2x = canvas.getContext('2d')
			var img = new Image
			img.onload = function() {
				canvas.width = img.width
				canvas.height = img.height
				c2x.drawImage(img, 0, 0)
				resolve(canvas.toDataURL())
				canvas.height = canvas.width = 0
			}
			img.onerror = reject
			img.src = path
			return
		}
		if (typeof plus === 'object') {
			plus.io.resolveLocalFileSystemURL(getLocalFilePath(path), function(entry) {
				entry.file(function(file) {
					var fileReader = new plus.io.FileReader()
					fileReader.onload = function(data) {
						resolve(data.target.result)
					}
					fileReader.onerror = function(error) {
						reject(error)
					}
					fileReader.readAsDataURL(file)
				}, function(error) {
					reject(error)
				})
			}, function(error) {
				reject(error)
			})
			return
		}
		if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
			wx.getFileSystemManager().readFile({
				filePath: path,
				encoding: 'base64',
				success: function(res) {
					resolve('data:image/png;base64,' + res.data)
				},
				fail: function(error) {
					reject(error)
				}
			})
			return
		}
		reject(new Error('not support'))
	})
}

export function base64ToPath(base64, extName) {
	console.log('base64')
	return new Promise(function(resolve, reject) {
		if (typeof window === 'object' && 'document' in window) {
			base64 = base64.split(',')
			var type = base64[0].match(/:(.*?);/)[1]
			var str = atob(base64[1])
			var n = str.length
			var array = new Uint8Array(n)
			while (n--) {
				array[n] = str.charCodeAt(n)
			}
			return resolve((window.URL || window.webkitURL).createObjectURL(new Blob([array], {
				type: type
			})))
		}
		var fileName;
		if (!extName) {
			extName = base64.match(/data\:\S+\/(\S+);/)
			if (extName) {
				extName = extName[1]
			} else {
				reject(new Error('base64 error'))
			}
			fileName = Date.now() + '.' + extName;
		} else {
			fileName = Date.now() + extName;
		}
		if (typeof plus === 'object') {
			var bitmap = new plus.nativeObj.Bitmap('bitmap' + Date.now())
			bitmap.loadBase64Data(base64, function() {
				var filePath = '_doc/uniapp_temp/' + fileName
				bitmap.save(filePath, {}, function() {
					bitmap.clear()
					resolve(filePath)
				}, function(error) {
					bitmap.clear()
					reject(error)
				})
			}, function(error) {
				bitmap.clear()
				reject(error)
			})
			return
		}
		if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
			var filePath = wx.env.USER_DATA_PATH + '/' + fileName
			wx.getFileSystemManager().writeFile({
				filePath: filePath,
				data: base64.replace(/^data:\S+\/\S+;base64,/, ''),
				encoding: 'base64',
				success: function() {
					resolve(filePath)
				},
				fail: function(error) {
					reject(error)
				}
			})
			return
		}
		reject(new Error('not support'))
	})
}

/**
 * H5端图片压缩
 *  参数说明：
 *  imgSrc 图片url
 *  scale缩放比例 0-1
 *  type 返回图片类型  默认blob 
 *  callback 回调设置返回值 
 */
export function translate(imgSrc, callback) {
	uni.showLoading({
		title: '正在上传',
		mask: true
	});
	// #ifdef H5
	var scale = 0.4;
	var type = 'base64';
	var img = new Image();
	img.src = imgSrc;
	img.onload = function() {
		var that = this;
		var h = that.height; // 默认按比例压缩
		var w = that.width;
		var canvas = document.createElement('canvas');
		var ctx = canvas.getContext('2d');
		var width = document.createAttribute("width");
		width.nodeValue = w;
		var height = document.createAttribute("height");
		height.nodeValue = h;
		canvas.setAttributeNode(width);
		canvas.setAttributeNode(height);
		ctx.drawImage(that, 0, 0, w, h);
		var base64 = canvas.toDataURL('image/jpeg', scale); //压缩比例
		canvas = null;
		if (type == 'base64') {
			uni.hideLoading();
			callback(base64);
		} else {
			uni.hideLoading();
			var blob = base64ToBlob(base64);
			var blobUrl = window.URL.createObjectURL(blob); //blob地址
			callback(blobUrl);
		}
	}
	// #endif
	// #ifdef APP-PLUS
	var scale = 30;
	plus.io.resolveLocalFileSystemURL(imgSrc, (entry) => { //通过URL参数获取目录对象或文件对象
		entry.file((file) => { // 可通过entry对象操作图片 
			console.log('压缩前图片信息:' + JSON.stringify(file)); //压缩前图片信息
			if (file.size > 204800) { //   如果大于500Kb进行压缩
				plus.zip.compressImage({ // 5+ plus.zip.compressImage 了解一下，有详细的示例
					src: imgSrc, //src: 压缩原始图片的路径    
					dst: imgSrc.replace('.png', 'yasuo.png').replace('.PNG',
							'yasuo.PNG').replace('.jpg', 'yasuo.jpg')
						.replace('.JPG', 'yasuo.JPG'),
					width: '40%', //dst: (String 类型 )压缩转换目标图片的路径，这里先在后面原始名后面加一个yasuo区分一下
					height: '40%', //width,height: (String 类型 )缩放图片的宽度,高度
					quality: scale, //quality: (Number 类型 )压缩图片的质量
					overwrite: true, //overwrite: (Boolean 类型 )覆盖生成新文件
					format:'jpg'   //format: (String 类型 )压缩转换后的图片格式
				}, (event) => {
					console.log('压缩后图片信息:' + JSON.stringify(event));
					//返回压缩后的图片路径
					callback(event.target);
					uni.hideLoading();
				}, function(err) {
					uni.hideLoading();
					console.log('Resolve file URL failed: ' + err.message);
				});
			} else { //else小于500kb跳过压缩，直接返回现有的src
				uni.hideLoading();
				callback(imgSrc);
	
			}
		});
	}, (e) => { // 返回错误信息
		uni.hideLoading();
		console.log('Resolve file URL failed: ' + e.message);
	});
	// #endif
}

// base转Blob
export function base64ToBlob(base64) {
	var arr = base64.split(','),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([u8arr], {
		type: mime
	});
}
